import { loginApi,logoutApi,getUserInfoApi } from "@/manager-core/api/login/login"



const state = () => ({
  hasinit: false,
  id : "",
  username: "",
  isadmin: "",
  rolename: "",
  auths: []
})

// getters
const getters = {
  username: (state:any, getters:any, rootState:any) => {
    return state.username;
  },

  isadmin: (state:any, getters:any, rootState:any) => {
    return state.isadmin;
  },

  rolename: (state:any, getters:any, rootState:any) => {
    return state.rolename;
  },

  id: (state:any, getters:any, rootState:any) => {
    return state.id;
  },

  auths: (state:any, getters:any, rootState:any) => {
    return state.auths;
  },
}

// actions
const actions = {

  LoginByUsername ({ state, commit }:any, {username,password}:any) {

    return new Promise((resolve,reject) =>{
      loginApi(username,password)
        .then((r:any)=>{
          resolve(r)
        })
        .catch((e:any)=>{
          reject(e);
        })
    })
  },

  GetUserInfo ({ state, commit }:any) {
    return new Promise((resolve,reject) =>{

      if(state.hasinit){
        resolve("true")
      }
      else {
        console.log("开始初始化信息")
        commit("setInit")
        // 检查初始化状态
        getUserInfoApi()
        .then((r:any)=>{
          console.log("getUserInfoApi",r);

          let data = {
            "id": r.muser.id,
            "username": r.username,
            "isadmin": r.isAdmin,
            "rolename": r.rolename,
            "auths": r.authorities,
          }

          commit("setUser",data)

          resolve(r)
        })
        .catch((e:any)=>{
          commit("clear")
          reject(e);
        })
      }

      


    })
  },

  logOutAction({state,commit}:any ){
    return new Promise((resolve,reject) =>{
      logoutApi()
        .then(()=>{
          commit("clear");
          resolve("success");
        })
        .catch((e:any)=>{
          reject(e);
        })
    });
  }
}

// mutations
const mutations = {
  setUser (state:any, payload:any) {
    state.id = payload.id;
    state.username = payload.username;
    state.isadmin = payload.isadmin;
    state.rolename = payload.rolename;
    state.auths = payload.auths;
  },

  setInit(state:any){
    state.hasinit = true;
  },

  clear (state:any) {
    state.hasinit = false;
    state.id = "";
    state.username = "";
    state.isadmin = "";
    state.rolename = "";
    state.auths = [];
  },

}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}